<?php
header('Content-Type: application/json; charset=utf-8');

/* 1. 数据库连接 */
$dbConfig = include('db_config.php');
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库连接失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 2. 取关键词 */
$keyword = $_POST['keyword'] ?? '';
if ($keyword === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '缺少参数 keyword'], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 3. 模糊搜索：标题/内容/标签 */
$like = '%' . $keyword . '%';
$sql = "
    SELECT *,
           CASE
               WHEN `title`   LIKE :k THEN 3
               WHEN `content` LIKE :k THEN 2
               ELSE 1
           END AS weight
    FROM `mi_bbs`
    WHERE `title`   LIKE :k
       OR `content` LIKE :k
       OR `tags`    LIKE :k
    ORDER BY weight DESC, `id` DESC
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':k' => $like]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($rows) {
        echo json_encode([
            'status' => 'success',
            'keyword'=> $keyword,
            'data'   => $rows,
            'total'  => count($rows)
        ], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode([
            'status'  => 'success',
            'keyword' => $keyword,
            'data'    => [],
            'total'   => 0,
            'message' => '没有找到相关文章'
        ], JSON_UNESCAPED_UNICODE);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '查询失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>
